﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using Common.Library;
using System.ComponentModel;
using OnlineVideos.Data;
using OnlineVideos.Entities;
using System.Windows.Controls.DataVisualization.Charting;
using OnlineVideos.ViewModels;
using MarkHeath.StarRating;
using System.Windows.Media.Imaging;
using System.Windows.Controls.DataVisualization;
using OnlineVideos.UI;
using System.Threading.Tasks;

namespace OnlineVideos.Views
{
    public partial class Details : PhoneApplicationPage
    {
        OnlineVideos.View_Models.ShowDetail showdetail;
        public Details()
        {
            InitializeComponent();
            Loaded += Details_Loaded;
            showdetail = new OnlineVideos.View_Models.ShowDetail();
        }
        public void Check()
        {
            bool img = ShellTileHelper.IsPinned(AppSettings.ShowID);
            if (img == true)
            {
                ((ApplicationBarMenuItem)ApplicationBar.MenuItems[0]).Text = "unpin from start page";
            }
            else
            {
                ((ApplicationBarMenuItem)ApplicationBar.MenuItems[0]).Text = "pin to start page";
            }
            if (FavoritesManager.IsFavoriteShow(AppSettings.ShowUniqueID))
                ((ApplicationBarMenuItem)ApplicationBar.MenuItems[3]).Text = "remove as favourite";
            else
                ((ApplicationBarMenuItem)ApplicationBar.MenuItems[3]).Text = "add as favourite";
        }
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
             string ShowId = string.Empty;
             if (NavigationContext.QueryString.TryGetValue("id", out ShowId))
             {
                 SettingsHelper.Save("id", ShowId);
             }
        }
        void Details_Loaded(object sender, RoutedEventArgs e)
        {
            Check();
            int showid = AppSettings.ShowUniqueID;
            if (Task.Run(async () => await Constants.connection.Table<ShowList>().Where(i => i.ShowID == showid).FirstOrDefaultAsync()).Result.Status == "Custom")
            {
                ((ApplicationBarMenuItem)ApplicationBar.MenuItems[1]).IsEnabled = true;
            }
            else
                ((ApplicationBarMenuItem)ApplicationBar.MenuItems[1]).IsEnabled = false;
            tblkVideosTitle.Text = OnlineShow.GetShowDetail(AppSettings.ShowUniqueID).Title;
            GetPageDataInBackground();
        }
      
        public void GetPageDataInBackground()
        {
            BackgroundHelper bwHelper = new BackgroundHelper();

            bwHelper.AddBackgroundTask(
                                        (object s, DoWorkEventArgs a) =>
                                        {
                                            a.Result = OnlineShow.RetriveChartDataForWebInfo(AppSettings.ShowUniqueID);
                                        },
                                        (object s, RunWorkerCompletedEventArgs a) =>
                                        {
                                            List<ChartProp> list = new List<ChartProp>();
                                            list = (List<ChartProp>)a.Result;
                                            if (list.Count == 0 )
                                            {
                                                list = OnlineShow.RetriveChartDataFromWebInfo(AppSettings.ShowUniqueID);
                                            }
                                            if (list.Count > 0)
                                            {
                                                if (list[0].type == "int")
                                                {
                                                    if (list.Where(i => i.value.ToString() == "0").Count() > 0)
                                                    {
                                                        ((ApplicationBarMenuItem)ApplicationBar.MenuItems[2]).IsEnabled = false;
                                                        ErrorText.Text = "Error";
                                                        ErrorText.Visibility = Visibility.Visible;
                                                        barstack.Visibility = Visibility.Collapsed;
                                                        Liststack.Visibility = Visibility.Collapsed;

                                                    }
                                                    else
                                                    {
                                                        ((ApplicationBarMenuItem)ApplicationBar.MenuItems[2]).IsEnabled = true;

                                                       
                                                        ErrorText.Visibility = Visibility.Collapsed;
                                                        barstack.Visibility = Visibility.Visible;
                                                        Liststack.Visibility = Visibility.Collapsed;
                                                        BarSeries b = (BarSeries)barChart.Series[0];
                                                        CategoryAxis Ca = new CategoryAxis();
                                                        Ca.Height = list.Count * 50;
                                                        b.IndependentAxis.DependentAxes.Add(Ca);
                                                        barChart.LegendStyle = hidelegend();
                                                        barChart.DataContext = list;

                                                    }
                                                }


                                                else
                                                {
                                                    if (list.Where(i => i.value.ToString() == "Error").Count() > 0)
                                                    {
                                                        ((ApplicationBarMenuItem)ApplicationBar.MenuItems[2]).IsEnabled = false;
                                                        ErrorText.Text = "Error";
                                                        ErrorText.Visibility = Visibility.Visible;
                                                        barstack.Visibility = Visibility.Collapsed;
                                                        Liststack.Visibility = Visibility.Collapsed;

                                                    }
                                                    else
                                                    {
                                                        ((ApplicationBarMenuItem)ApplicationBar.MenuItems[2]).IsEnabled = false;
                                                        ErrorText.Visibility = Visibility.Collapsed;
                                                        FavImage.Source = new BitmapImage(new Uri(list[0].FavUri, UriKind.RelativeOrAbsolute));
                                                        tbTitle.Text = list[0].Title;
                                                        webBrowser1.NavigateToString(list[list.Count - 1].value.ToString());
                                                        barstack.Visibility = Visibility.Collapsed;
                                                        Liststack.Visibility = Visibility.Visible;
                                                    }

                                                }
                                              
                                            }
                                            else
                                            {
                                                ErrorText.Visibility = Visibility.Visible;
                                                barstack.Visibility = Visibility.Collapsed;
                                                Liststack.Visibility = Visibility.Collapsed;
                                            }
                                        
                                        }
                                      );
            bwHelper.RunBackgroundWorkers();
        }
        public  Style hidelegend()
        {
            Style legendStyle = new Style(typeof(Legend));
            legendStyle.Setters.Add(new Setter(Legend.VisibilityProperty, Visibility.Collapsed));
            legendStyle.Setters.Add(new Setter(Legend.WidthProperty, 0));
            legendStyle.Setters.Add(new Setter(Legend.HeightProperty, 0));
            return legendStyle;
        }
        private void rate_Click(object sender, EventArgs e)
        {
         
            StarRatingControl starratingcontrol = new StarRatingControl();
            int showid = AppSettings.ShowUniqueID;
            starratingcontrol.Rating = Convert.ToInt32(Task.Run(async () => await Constants.connection.Table<ShowList>().Where(i => i.ShowID == showid).FirstOrDefaultAsync()).Result.Rating);
            showdetail.RateThisShow(starratingcontrol);
        }

        private void Fav_Click(object sender, EventArgs e)
        {
            try
            {
                ApplicationBarMenuItem am = sender as ApplicationBarMenuItem;
                FavoritesManager.SaveFavorites(AppSettings.ShowUniqueID);

                if (FavoritesManager.IsFavoriteShow(AppSettings.ShowUniqueID))
                    am.Text = "remove as favourite";
                else
                    am.Text = "add as favourite";
            }
            catch (Exception ex)
            {
            }
        }

        private void Browser_Click(object sender, EventArgs e)
        {
            NavigationService.Navigate(new Uri("/Views/UserBrowserPage.xaml", UriKind.Relative));
        }

        protected override void OnBackKeyPress(System.ComponentModel.CancelEventArgs e)
        {

            if (AppSettings.bcount)
            {
                e.Cancel = true;
             
            }

            AppSettings.detailtocast = 0;
          

            base.OnBackKeyPress(e);
        }

        private void TextList_SelectionChanged_1(object sender, SelectionChangedEventArgs e)
        {
            OnlineVideos.ViewModels.Details.cp = (sender as ListBox).SelectedItem as ChartProp;
            NavigationService.Navigate(new Uri("/Views/DetailsBrowserPage.xaml", UriKind.Relative));
        }

        private void share_Click(object sender, EventArgs e)
        {
            NavigationService.Navigate(new Uri("/Views/userSharePage.xaml", UriKind.Relative));
        }

        private void Reminder_Click_1(object sender, EventArgs e)
        {
            NavigationService.Navigate(new Uri("/Views/RemindersAlarms.xaml", UriKind.Relative));
        }

        private void pin_Click_1(object sender, EventArgs e)
        {
            ShellTileHelper.PinMovieToStartScreen(AppSettings.ShowID);
             bool img = ShellTileHelper.IsPinned(AppSettings.ShowID);
             ApplicationBarMenuItem am = sender as ApplicationBarMenuItem;
             if (img == true)
             {
                 am.Text = "unpin from start page";
             }
             else
             {
                 am.Text = "pin to start page";
             }
        }
    }
}